﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace _443_Server
{
	public class Login
	{
		public static void PerformLogin(Player p)
		{
			int nameHash = p.NetworkInStream.ReadByte();
			p.NetworkOutStream.WriteByte(0); //Type

			long key = new Random().Next(999999999) * 999999999;
			p.OutStream.WriteQWord(key);
			p.Flush();

			int connectionType = p.NetworkInStream.ReadByte();
			int packetSize = p.NetworkInStream.ReadByte();
			p.Fill(packetSize);

			int version = p.InStream.ReadDWord();
			bool detail = (p.InStream.ReadByte() == 1 ? true : false);

			//Read all index checksums
			for (int i = 0; i < 14; i++)
				p.InStream.ReadDWord();

			if (p.InStream.ReadByte() != 10)
				return;

			int[] keys = new int[4];
			keys[0] = p.InStream.ReadDWord();
			keys[1] = p.InStream.ReadDWord();
			keys[2] = p.InStream.ReadDWord();
			keys[3] = p.InStream.ReadDWord();
			for (int i = 0; i < 4; i++)
				keys[i] += 50;
			//We're not using packet encryption anyway, so who cares!
			int unknown = p.InStream.ReadDWord();
			long username = p.InStream.ReadQWord();
			string password = p.InStream.ReadNewString();
			p.EncodedName = username;
			p.Username = Utility.LongToString(username);
			p.Password = password;

			//next byte is return code
			if (password != "1" && password != "")
			{
				p.NetworkOutStream.WriteByte(3);
				return;
			}

			p.NetworkOutStream.WriteByte(2);

			p.NetworkOutStream.WriteByte(0); //rights
			p.NetworkOutStream.WriteByte(0); //some sort of flag
			p.NetworkOutStream.WriteByte(0); p.NetworkOutStream.WriteByte(1); //player index
			p.NetworkOutStream.WriteByte(0); //not sure

			Console.WriteLine(p.Username + " has logged in with password " + p.Password + " from " + p.Socket.RemoteEndPoint.ToString() + ".");
		}
	}
}
